package com.credithc.signature.common.service.lanmao;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.credithc.signature.common.utils.EncoderUtils;
import com.credithc.signature.common.utils.HttpClientSender;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;

@Service
@Slf4j
@Data
public class LanmaoSdkClient {
    @Value("${cat.sdk.host:http://10.150.30.56:8080/openapi/api/v1.0}")
    private  String host;
    @Value("${cat.sdk.privateKey:MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBANBl14vy6b5/bMz2mFvstUhtt/yW55wpy4sK3vNXJKsUbFj0ey6DxpCcHDd2Hzflw5e3XXpfJPxkAGs7ug7KmjuCsc71Jkhp6p/NsdyqM7D3BMpQ2958+PGbim+7iY6J8mIbmpbTPIFeVtZUFlzK/9h6DT5yARtby2FMSeV3ZPXXAgMBAAECgYEAv1aCTRA+5JUCRD21LdFrsJBseRHknVESfRsCENJV7G3X/OSbpN2Alo1+qr1ddGkU6FuHDDAHOWRnrg0siyAh8hE6IU5uqypw9+l1AHacAcYeA9DDBY9z7LxuWFdxZ53eb9LJZ1ekPpbNv4E3yi7Pht2X3oQG4Ay9+5ADlGnwFMECQQDx2LZdSLf2Arq7u8DDyerXukGo2HJC5YT450HiMuvJMzypL4IxRPuBSungM19XVcSsieTEWdJbgwHfsl2vRFY5AkEA3JgCR8eJTO8veqJsg/IaP+X3iHM8xT3mcqJGG97z9yCITHI4E5R8gfcm6duOR6p2LatkllVCNmzKKzrZZJ8sjwJBANyd3H3sQCRjCQUImSgBogF5Hzxvdowf49VK4Ib//Kdl3ghYFmPrkaK4O/ER6/83dloO0Gltpr9kGul9RIkFxcECQHux7U1ssSvnz1rX6zuNrXR5MnVcEQ6VKDzNi7yjJ3BC2MrtHU61a5/BBBwMVlsPVddEDVJTGp7EIBVfmXlX3DcCQQDuZvWkfs9OJfV8YxkkiRgEsxXy8zLVwdPhUeepCMyFryFBfDthtg42UHaT2pxxeuGH8KvrDkNg8TI3LG/YJmn7}")
    private String pryKey;

    private PrivateKey privateKey;

    /**

     * @return
     */
    @PostConstruct
    public void init() {
        // 生成私钥
        PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(EncoderUtils.base64Decode(pryKey.getBytes()));
        KeyFactory keyf;
        try {
            keyf = KeyFactory.getInstance("RSA");
            PrivateKey priKey = keyf.generatePrivate(priPKCS8);
            this.privateKey = priKey;
        } catch (NoSuchAlgorithmException e) {
            log.error("工具类LanmaoSdkClient[init]方法发生异常-无此算法", e);
        } catch (InvalidKeySpecException e) {
            log.error("工具类LanmaoSdkClient[init]方法发生异常-无效的key", e);
        }
    }

    /**
     * 发送post请求
     * @param method
     * @param data
     * @return
     * @throws Exception
     */
    public JSONObject post(String method, JSONObject data) throws Exception{

        String sign = signSignature(data.toJSONString().getBytes("utf-8"));
        //报文签名
        data.put("sign", sign);
        // 发送请求

        String responseBody = HttpClientSender.sendHttpPost(host, method, data.toJSONString());
        // 返回结果解析
        JSONObject userObj = JSON.parseObject(responseBody);
        return userObj;
    }

    /**
     * 进行数字签名
     * @param degistData 待签名数据
     * @return
     */
    public String signSignature(byte[] degistData){
        String sign = null;
        byte[] signed = null;
        try{
            /* 用私钥对摘要数据进行数字签名  */
            Signature signature = Signature.getInstance("SHA1withRSA");
            // 生成私钥
            signature.initSign(privateKey);
            signature.update(degistData);
            /* 生成数字签名  */
            signed = signature.sign();
            sign = EncoderUtils.base64EncodeToString(signed);
            signed = null;
        }catch(Exception e){
            log.error("工具类LanmaoSdkClient[signSignature]方法发生异常", e);
        }
        return sign;
    }


}
